package tank.client.game;

import tank.client.GameClient;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Map;

import static tank.client.GameClientHandler.PANEL_HEIGHT;
import static tank.client.GameClientHandler.PANEL_WIDTH;

public class MyPanel extends JPanel implements KeyListener {


    private Stage currentStage;

    public Stage getCurrentStage() {
        return currentStage;
    }

    public void setCurrentStage(Stage currentStage) {
        this.currentStage = currentStage;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT);
        if(currentStage != null && currentStage.getHeros() != null) {
            Map<String, Hero> heros = currentStage.getHeros();
            for (String key : heros.keySet()) {
                Hero hero = heros.get(key);
                if(hero.getLive() > 0){
                    if(key.equals(GameClient.remoteAddress)){
                        hero.drawSelf(g);
                    }else {
                        hero.drawTank(g);
                    }
                }else if(!hero.isRemoved()){
                    hero.drawBoom(g);
                }
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    private long lastPressed = System.currentTimeMillis();

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()){
            case KeyEvent.VK_UP:
            case KeyEvent.VK_DOWN:
            case KeyEvent.VK_LEFT:
            case KeyEvent.VK_RIGHT:
            case KeyEvent.VK_SPACE:
                long now = System.currentTimeMillis();
                if(now - lastPressed > 400){
                    GameClient.send(""+e.getKeyCode());
                    lastPressed = now;
                }
            break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }


}
